const path = require('node:path');
const { app, BrowserWindow, ipcMain, session } = require('electron');
const { log } = require('console');

const isDev = !app.isPackaged;
let mainWindow = null;
let testWindows = [];

function createWindow() {
  /**
   * Electron中新建的所有的窗口默认共用一个session
   * 这里为了方便测试，给每个窗口分配一个唯一的partition，保证每个窗口有独立的localstorage，避免hooks自动登录
   */
  const partition = `persist:test_window_${Date.now()}`
  // 清空session缓存
  session.fromPartition(partition).clearCache().then(() => {
    log(`Cache for partition ${partition} cleared.`);
  });

  mainWindow = new BrowserWindow({
    width: 1200,
    height: 800,
    minWidth: 1200,
    minHeight: 800,
    frame: false,
    titleBarStyle: 'hidden',
    webPreferences: {
      preload: path.join(__dirname, 'preload.js'),
      nodeIntegration: false,
      contextIsolation: true,
      partition: isDev && partition,
    },
  });
  // chromium接入的url 开发环境我们的前端为3000
  const url = isDev
    ? 'http://localhost:3000'
    : `file://${path.join(__dirname, '../out/index.html')}`;
  log('url', url);
  
  const loadUrlWithRetry = (url, retries = 5, delay = 1000) => {
    mainWindow.loadURL(url).catch((err) => {
      log(`Failed to load URL: ${url}. Retries left: ${retries}`);
      if (retries > 0) {
        setTimeout(() => {
          loadUrlWithRetry(url, retries - 1, delay);
        }, delay);
      } else {
        log('Failed to load URL after multiple retries.', err);
      }
    });
  };

  loadUrlWithRetry(url);

  if (isDev) {
    // 开发者工具是否打开
    mainWindow.webContents.openDevTools();
  }

  // 清理
  mainWindow.on('closed', () => {
    mainWindow = null;
  });
}

function createTestWindow(windowId = Date.now()) {
  const partition = `persist:test_window_${windowId}`; // 每个窗口唯一 session

  const testWindow = new BrowserWindow({
    width: 1200,
    height: 600,
    minWidth: 1200,
    minHeight: 800,
    frame: true,
    title: `测试窗口 ${windowId}`,
    webPreferences: {
      preload: path.join(__dirname, 'preload.js'),
      nodeIntegration: false,
      contextIsolation: true,
      partition, // 关键设置
    },
  });

  const url = isDev
    ? 'http://localhost:3000'
    : `file://${path.join(__dirname, '../out/index.html')}`;

  testWindow.loadURL(url);

  if (isDev) {
    testWindow.webContents.openDevTools();
  }

  testWindow.on('closed', () => {
    testWindows = testWindows.filter(win => win !== testWindow);
  });

  testWindows.push(testWindow);
  return testWindow;
}

// IPC处理器
ipcMain.handle('create-test-window', () => {
  return createTestWindow();
});

// IPC处理器
ipcMain.handle('close-all-test-windows', () => {
  testWindows.forEach(win => {
    if (!win.isDestroyed()) {
      win.close();
    }
  });
  testWindows = [];
});

app.whenReady().then(() => {
  log('whenReady async');
  createWindow();

  app.on('activate', () => {
    if (BrowserWindow.getAllWindows().length === 0) createWindow();
  });
});

app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') app.quit();
});
